package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.entity.User;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.example.util.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Boolean isValidRegistrationRequest(User user) {
        if (user == null) {
            return false;
        }
        if (user.getUserName() == null || user.getUserName().isEmpty()) {
            return false;
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            return false;
        }
        if (user.getPhone() == null || user.getPhone().isEmpty()) {
            return false;
        }
        if (user.getEmail() == null || user.getEmail().isEmpty()) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean isExistsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    @Override
    public Boolean isExistsByPhone(String phone) {
        return userMapper.existsByPhone(phone);
    }

    @Override
    public Boolean isExistsByEmail(String email) {
        return userMapper.existsByEmail(email);
    }

    @Override
    public User authenticate(String email, String password) throws NoSuchAlgorithmException {
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("email", email).eq("password", KeyUtil.Md5(password));
        User user = userMapper.selectOne(wrapper);
        return user;
    }

}
